package be.ipl.pigolo.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.pigolo.usecases.GestionPartie;

/**
 * Servlet implementation class Deconnexion
 * 
 * @author lspitaels,sdoublier
 */
@WebServlet(name = "deconnect.html")
public class Deconnexion extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	GestionPartie gestPartie;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();

		String username = "";
		gestPartie = null;

		synchronized (session) {
			username = (String) session.getAttribute("fermier");
			gestPartie = (GestionPartie) session.getAttribute("gestionpartie");

			request.getSession().removeAttribute("fermier");
			request.getSession().removeAttribute("gestionpartie");
			request.getSession().removeAttribute("nomPartie");
		}

		try {
			gestPartie.deconnexion(username);
		} catch (Exception e) {
			response.sendRedirect(response
					.encodeRedirectURL("accueil.html?erreur=Problème de login :<br>"
							+ e.getMessage()));
		}
		response.sendRedirect(response.encodeRedirectURL("index.html"));
	}

}
